package com.itany.crawler;

import com.itany.ApplicationContextHolder;
import com.itany.book.service.impl.BookServiceImpl;
import com.itany.pojo.BookWithBLOBs;
import com.itany.service.BookService;
import com.itany.utils.Log;
import com.itany.utils.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class ThirdHandle extends UrlBaseHandle {

    private static BookService bookService;

    static {
        bookService = ApplicationContextHolder.getBean(BookServiceImpl.class);
    }

    static String url_sec = "http://www.bookschina.com//6366979.htm";

    public ThirdHandle() {
    }

    public ThirdHandle(String url, boolean proxyed) {
        super(url, proxyed);
//        setUrl(url_sec);
    }

    @Override
    public String handle(Urls urls) throws Exception {
        BookWithBLOBs book = new BookWithBLOBs();

        //获取页面html代码
        String html = doGet();
        //将html字符串解析成dom对象
        Document document = Jsoup.parse(html, "UTF-8");

        // 解析页面---------------------------------------------------------------------------------
        try {
            String imgLink = null;
            // 图片
            try {
                Element bigImgSrc = document.getElementById("bigImgSrc");
                if (bigImgSrc != null) {
                    imgLink = bigImgSrc.attr("value");
                    System.out.println("图片路径 :" + imgLink);

                }
            } catch (Exception e) {
                System.out.println("图片解析错误：" + getUrl());
            }

            Element bookInfo = document.getElementsByClass("bookInfo").get(0);
            String bookName = null;
            try {
                bookName = bookInfo.getElementsByTag("h1").get(0).text();
                System.out.println("书籍名称 :" + bookName);
            } catch (Exception e) {
                System.out.println("书籍解析错误：" + getUrl());
            }


//            String recomandInfo = null;
//            Elements recomands = bookInfo.getElementsByClass("recomand");
//            if (recomands.size() > 0) {
//                recomandInfo = recomands.get(0).text();
//            }
//            System.out.println("推荐信息 :" + recomandInfo);

            String author = null;
            try {
                Elements authors = bookInfo.getElementsByClass("author");
                if (authors.size() > 0) {
                    author = authors.get(0).getElementsByTag("a").get(0).text();
                }
            } catch (Exception e) {
                System.out.println("书籍作者解析错误：" + getUrl());
            }

            String publishname = null;
            try {
                Element publisher = bookInfo.getElementsByClass("publisher").get(0);
                publishname = publisher.getElementsByTag("a").get(0).text();
                String publishDate = publisher.getElementsByTag("i").get(0).text();
                System.out.println("出版商 :" + publishname + " 出版时间 :" + publishDate);
            } catch (Exception e) {
                System.out.println("出版社解析错误：" + getUrl());
            }
//
//        Element otherInfor = bookInfo.getElementsByClass("otherInfor").get(0);
//        String em = otherInfor.getElementsByTag("em").get(0).text();
//        String pageSize = otherInfor.getElementsByTag("i").get(0).text();
//        System.out.println("开本 :" + em + " 页数 :" + pageSize);

//        String score = bookInfo.getElementsByClass("startWrap").get(0).getElementsByTag("em").get(0).text();
//        System.out.println("评分 :" + score);

            String price = null;
            String sellPrice = null;
            try {
                sellPrice = bookInfo.getElementsByClass("sellPrice").get(0).text();
                price = bookInfo.getElementsByClass("price").get(0).text();
                System.out.println("中图价 :" + sellPrice + " 原价 :" + price);
            } catch (Exception e) {
                System.out.println("价格解析错误 :" + getUrl());
            }

            String isbn = null;
            String barcode = null;
            String zhuangzhen = null;
            String banci = null;
            String ceshu = null;
            String weight = null;
            String yinshuacishu = null;
            String fenlei1 = null;
            String fenlei2 = null;
            try {
                Element copyrightInfor = document.getElementById("copyrightInfor");
                Elements lis = copyrightInfor.getElementsByTag("li");
                isbn = lis.get(0).text();
                barcode = lis.get(1).text();
                zhuangzhen = lis.get(2).text();
                banci = lis.get(3).text();
                ceshu = lis.get(4).text();
                weight = lis.get(5).text();
                yinshuacishu = lis.get(6).text();
                fenlei1 = lis.get(7).getElementsByTag("a").get(0).text();
                fenlei2 = lis.get(7).getElementsByTag("a").get(1).text();
            } catch (Exception e) {
                System.out.println("详情信息解析错误" + getUrl());
            }

//
//            System.out.println("isbn :" + isbn + " 条形码 :" + barcode + "装帧 :" + zhuangzhen + " 班次 :" + banci
//                    + " 册数 :" + ceshu + " 重量 :" + weight + " 印刷次数 :" + yinshuacishu + " 分类1 :" + fenlei1 + " 分类2 :" + fenlei2);


//            Element specialist = document.getElementById("specialist");
//            // 本书特色没有
//            if (specialist != null) {
//                String specialistText = specialist.getElementsByTag("p").get(0).text();
//                System.out.println("本书特色 :" + specialistText);
//            }

            Element catalogSwitch = document.getElementById("catalogSwitch");
            //目录
            String catalog = null;
            if (catalogSwitch != null) {
                catalog = catalogSwitch.text();
                System.out.println("目录 :" + catalog);
            }

            //内容简介
            String contentInfo = null;
            try {
                Element brief = document.getElementById("brief");
                contentInfo = null;
                if (brief != null) {
                    contentInfo = brief.getElementsByTag("p").get(0).text();
                    System.out.println("内容简介 ：" + contentInfo);
                }
            } catch (Exception e) {
                System.out.println("内容简介解析错误" + getUrl());
            }

            //
            String authorInfo = null;
            try {
                Element zuozhejianjie = document.getElementById("zuozhejianjie");
                if (zuozhejianjie != null) {
                    authorInfo = zuozhejianjie.getElementsByTag("p").get(0).text();
                    System.out.println("作者简介 :" + authorInfo);
                }
            } catch (Exception e) {
                System.out.println("作者简介解析出错" + getUrl());
            }

            urls.count++;

//            List<String> lines = new ArrayList<>();
//            lines.add(bookName + "\t" + isbn + "\t" + imgLink);
////        lines.add(isbn);
////        lines.add(imgLink);
//            lines.add("");
//
//
//            Files.write(Paths.get(Main.testDataPath, "data.txt"), lines,
//                    StandardOpenOption.CREATE, StandardOpenOption.APPEND);

            book.setBookname(bookName);
            book.setImgurl(imgLink);
            book.setIsbn(StringUtils.getIsbn(isbn));
            book.setBarcode(barcode);
            book.setNumber(0);
            book.setFormat(yinshuacishu);
            book.setBookintroduce(contentInfo);
            book.setAuthorintroduce(authorInfo);
            book.setCatalog(catalog);
            book.setPrice(StringUtils.getPrice(price));
            book.setGroupprice(StringUtils.getPrice(sellPrice));
            book.setAuthor(author);
            book.setFlag(1);
            bookService.addBook(book,
                    StringUtils.trim(publishname),
                    StringUtils.trim(fenlei1),
                    StringUtils.trim(fenlei2));


        } catch (Exception e) {
            Log.logErr("页面解析出错未知错误" + e.getMessage() + "\t " + getUrl());
        }
        return null;
    }


    public static void main(String[] args) throws Exception {
        ThirdHandle handle = new ThirdHandle(url_sec, false);
        handle.handle(new Urls());

        System.out.println("成功了吗");


    }

}
